import { combineReducers } from "redux";
import uuid from "uuid-v4";

// countReducer
const data = {
  name: "djk",
  age: 18,
  count: 10,
};
function countReducer(state = data, action) {
  console.log("接收到action", action);
  if (action.type === "ADD_NUM") {
    let num = state.count + action.num;
    // console.log(num);
    // 如果reducer处理的是一个复杂的对象，则需要在改变它单独的一个
    // 属性的时候，需要把整个的对象都给他复制一遍
    return { ...state, count: num };
  } else if (action.type === "SUB_NUM") {
    let num = state.count - action.num;
    return { ...state, count: num };
  } else if (action.type === "AAA") {
    return { ...state, name: "tom" };
  } else {
    return state;
  }
}

// 如果保存的数据是单独的一个，可以这么干
// function reducer(state = 0, action) {
//   console.log("接收到action", action);
//   if (action.type === "ADD_NUM") {
//     return state + action.num;
//   }
//   return state;
// }

// todosReducer
const defaultTodos = [
  {
    id: 1,
    name: "吃饭",
    done: true,
  },
  {
    id: 2,
    name: "睡觉",
    done: false,
  },
  {
    id: 3,
    name: "打豆豆",
    done: true,
  },
];
function todosReducer(state = defaultTodos, action) {
  if (action.type === "ADD_TODO") {
    const todo = {
      id: uuid(),
      name: action.name,
      done: false,
    };
    return [todo, ...state];
  } else if (action.type === "DEL_TODO") {
    return state.filter((item) => item.id !== action.id);
  } else {
    return state;
  }
}
// 合并两个reducer
export default combineReducers({
  count: countReducer,
  todos: todosReducer,
});
